package net.wenku8.reader.view.file

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson2.JSON
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.entity.BookFileChapter
import net.wenku8.reader.enums.FileBookInfo
import net.wenku8.reader.enums.FileBookText
import net.wenku8.reader.service.FileService
import net.wenku8.reader.state.StateReadFile
import net.wenku8.reader.view.common.BaseViewModel

class FileReadViewModel : BaseViewModel() {

    private var chapterIndex = 0
    private var chapterList = ArrayList<BookFileChapter>()
    var chapter by mutableStateOf(BookFileChapter())
    var loaded by mutableStateOf(false)
    val textList = mutableStateListOf<String>()

    fun initData() {
        chapter = StateReadFile.chapter.value
        chapterList = StateReadFile.chapterList.value
        loadBookData()
        loaded = true
    }


    fun changeChapter(left: Boolean){
        val nextChapter = getNextChapter(left)
        if (nextChapter != null){
            chapter = nextChapter
            textList.clear()
            loadBookData()
        }
    }


    private fun loadBookData(){
        viewModelScope.launch(Dispatchers.IO) {
            val bookId = StateReadFile.bookFile.value.bookId
            val lineList = FileService.readAsLine(FileBookText +bookId) ?: return@launch
            chapterIndex = chapter.chapterIndex
            val lineStart = chapter.chapterLineStart
            var lineEnd = chapter.chapterLineEnd
            lineEnd = if (lineEnd != 0)  lineEnd else lineList.size
            textList.clear()
            textList.addAll(lineList.subList(lineStart, lineEnd).filter { it.trim().isNotEmpty() })
            saveReadHis()
        }
    }

    private fun getNextChapter(left : Boolean): BookFileChapter?{
        val nextIndex = if (left) chapterIndex + 1 else chapterIndex - 1
        if (!left && nextIndex < 0 || left && nextIndex >= chapterList.size){
            return null
        }
        chapterIndex = nextIndex
        return chapterList[nextIndex]
    }

    private fun saveReadHis(){
        val bookId = StateReadFile.bookFile.value.bookId
        StateReadFile.bookFile.value.lastRead = chapter
        FileService.writeFile(FileBookInfo+bookId, JSON.toJSONString(StateReadFile.bookFile))
    }
}
